package com.gm.wholesale.module.main.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.base.baseui.baseactivity.BaseActivity;
import com.gm.commonlib.module.evenbus.EventMessage;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.util.logUtils.LogUtil;
import com.gm.commonlib.util.permission.PermissionUtil;
import com.gm.commonlib.util.permission.interfaces.IPermissionCallback;
import com.gm.commonlib.views.dialog.DialogUtil;
import com.gm.commonlib.views.popupwindow.Popupwindow;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.GMApplication;
import com.gm.wholesale.R;
import com.gm.wholesale.bluetooth.BluetoothUtil;
import com.gm.wholesale.bluetooth.DeviceManger;
import com.gm.wholesale.bluetooth.bean.DeviceBean;
import com.gm.wholesale.bluetooth.bean.WeightBean;
import com.gm.wholesale.bluetooth.interfaces.OnConnectionBluListener;
import com.gm.wholesale.bluetooth.weightBlue.WeightBlueManger;
import com.gm.wholesale.cacheData.PatchCache;
import com.gm.wholesale.constant.Constant;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.evenbus.EventBusType;
import com.gm.wholesale.constant.MenuData;
import com.gm.wholesale.module.appUpdate.UpdateAppUtil;
import com.gm.wholesale.module.config.ConfigData;
import com.gm.wholesale.module.custom.ChoiceCustomData;
import com.gm.wholesale.module.custom.bean.CustomBean;
import com.gm.wholesale.module.custom.bean.DefaultCustomBean;
import com.gm.wholesale.module.custom.model.CustomModel;
import com.gm.wholesale.module.custom.view.CustomView;
import com.gm.wholesale.module.good.bean.GoodBean;
import com.gm.wholesale.module.good.bean.GoodListBean;
import com.gm.wholesale.module.main.listener.MyDrawerLayoutListener;
import com.gm.wholesale.module.main.presenter.CreateOrderUiPre;
import com.gm.wholesale.module.main.presenter.MainPresenter;
import com.gm.wholesale.module.main.presenter.VoiceViewPresenter;
import com.gm.wholesale.module.order.bean.OrderDetailBean;
import com.gm.wholesale.module.voice.VoiceManger;
import com.gm.wholesale.module.voice.voiceCreateOrder.VoiceCreateOrderManger;
import com.gm.wholesale.util.AppUtil;
import com.gm.wholesale.util.ViewUtil;
import com.gm.wholesale.view.HeaderView;
import com.taobao.sophix.SophixManager;

import java.util.Set;

public class MainActivity extends BaseActivity {

    public HeaderView mHeaderView; //title
    private DrawerLayout mDrawerLayout; //侧滑控件
    private LeftMenuFragment mLeftMenuFragment; //侧滑菜单

    public CreateOrderUiPre mCreateOrderUiPre; //创建单子界面

    private VoiceViewPresenter mVoiceViewPresenter;
    public boolean mIsConnection;
    private CustomView mCustomView;

    public GMApplication getGMApplication() {
        return (GMApplication) getBaseApplication();
    }

    public static MainActivity mActivity;

    public boolean mIsNeedNt;
    private ConfigData sConfigData;

    private MenuData mCurrentMenuData;

    private MainPresenter mainPresenter;

    private ConnectionListener mListener;
    private WeightBlueManger mWeightBlueManger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        PatchCache.clearnOldCacheData();
        loadNewPatch();
        registerReStartApp();
        mListener = new ConnectionListener();
        sConfigData = ConfigData.getConfigData();
        mActivity = this;
        setContentView(R.layout.activity_main);
        mainPresenter = new MainPresenter(this);
        initView();
        initPresenter();
        handelViewByPermission();

    }
    //todo 加载阿里后台发布的补丁包
    private void loadNewPatch(){
        if (!PatchCache.isOutMaxLoadSize()){
            SophixManager.getInstance().queryAndLoadNewPatch();
            PatchCache.saveLoadSize();
            LogUtil.d("查询补丁");
        }
        else {
            LogUtil.d("查询补丁次数已达上限");
        }

    }
    private void registerReStartApp(){
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(Constant.reStartApp);
        registerReceiver(new ReStartApp(),intentFilter);
    }
    class ReStartApp extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            DialogUtil.show(getActivity(), "补丁下载成功，请重启应用", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                    AppUtil.exitApp();
                    System.exit(0);
                }
            });

        }
    }


    //todo 更具权限不同，显示不同得界面
    private void handelViewByPermission() {
        if (sConfigData == null) { //todo 按道理不可能走这里，防止空指针做个处理
            mainPresenter.showOrderMangerUI();
            mHeaderView.hidBackView();
            return;
        }
        if (!sConfigData.hasCreateOrderPermission()) { //没有开单权限，进入订单管理界面
            mainPresenter.showOrderMangerUI();
            mHeaderView.hidBackView();
        } else {
            mWeightBlueManger = WeightBlueManger.newInstance();
            mWeightBlueManger.initWeightBlue(getActivity());
            startConnectionBlue();
            //获取默认散户数据
            getDefaultCustom();
            //语音录单权限
            if (sConfigData.hasVoicePermission()) {
                VoiceManger.init(this);
            }
        }

    }

    @Override
    protected void onResume() {
        UpdateAppUtil.getAppVersion(this);
        super.onResume();
    }


    class ConnectionListener implements OnConnectionBluListener {

        @Override
        public void connection(DeviceBean deviceBean) {
            mIsNeedNt = false;
            mIsConnection = true;
            ToastUtil.showToast("连接蓝牙秤成功");
            if (deviceBean != null) {
                DeviceManger.getDeviceManger().saveWeightDevice(deviceBean);
            }
            EvenBusUtil.connectionSuccess();
            hidLoadingDialog();
        }

        @Override
        public void connectionFail() {
            if (isFinishing()) {
                return;
            }
            if (mWeightBlueManger != null) {
                mWeightBlueManger.setFailState();
            }
            if (mIsNeedNt) {
                DialogUtil.showConnectionWeightFail(getContext());
                mIsNeedNt = false;
            }
            hidLoadingDialog();
            mIsConnection = false;
            DeviceManger.getDeviceManger().cleanWeightDevice();
            EvenBusUtil.connectionFail();
        }

        @Override
        public void getNumber(WeightBean weightBean) {
            if (mCreateOrderUiPre != null) {
                mCreateOrderUiPre.setNumBer(weightBean);
            }
            VoiceCreateOrderManger.newInstance().setWeightBean(weightBean);
        }
    }


    public void startConnectionBlue() {
        mIsNeedNt = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PermissionUtil.aplyBluePermission(this, new IPermissionCallback() {
                @Override
                public void onPermissionResult(boolean result, Set<String> dataSet) {
                    if (result && mWeightBlueManger != null) {
                        mWeightBlueManger.connectionWeightBlue(getActivity(), mListener);
                    } else {
                        BluetoothUtil.showNotPermiss();
                        ViewUtil.showPrintError();
                    }
                }
            });
        } else {
            PermissionUtil.aplyLocationPermission(this, new IPermissionCallback() {
                @Override
                public void onPermissionResult(boolean result, Set<String> dataSet) {
                    if (mWeightBlueManger != null) {
                        mWeightBlueManger.connectionWeightBlue(getActivity(), mListener);
                    }

                }
            });

        }


    }


    //todo 初始创建订单控制器
    private void initPresenter() {
        mCreateOrderUiPre = new CreateOrderUiPre(this, mainPresenter.mMainOrderFragment);
    }


    //获取默认散户信息
    public void getDefaultCustom() {
        CustomModel.getDefaultCustom(null, new BaseHttpObserver<DataResp<DefaultCustomBean>>() {
            @Override
            protected void handleResultOkResp(DataResp<DefaultCustomBean> resp) {
                DefaultCustomBean defaultCustomBean = resp.getData();
                if (defaultCustomBean != null) {
                    CustomBean customBean = new CustomBean();
                    customBean.setName(defaultCustomBean.getName());
                    customBean.setId(defaultCustomBean.getId());
                    ChoiceCustomData.newInstance().setCustomBean(customBean);
                    ChoiceCustomData.newInstance().setSanKeCustomBean(customBean);
                    EvenBusUtil.updateHomeDefaultCustorm(customBean);
                }
            }
        }.setAutoErrorToast(false));
    }


    // todo 弹出先择客户的界面
    public void showChoiceCustom(View view) {
        if (mCustomView == null) {
            mCustomView = new CustomView(mActivity);
        } else {
            mCustomView.updateView();
        }
        mCustomView.setCustomChoiceListener(customBean ->
                EvenBusUtil.updateHomeDefaultCustorm(customBean)
        );
        Popupwindow.showPopCenterView(mActivity, mCustomView);

    }

    // todo 创建订单界面，输入数量单价
    public void showCreateOrderView(GoodBean goodBean) {
        if (mCreateOrderUiPre == null) return;
        mCreateOrderUiPre.showCreateOrderView(goodBean);
    }


    //显示语音输入view
    public void startVoice() {
        if (mVoiceViewPresenter == null) {
            mVoiceViewPresenter = new VoiceViewPresenter();
        }
        mVoiceViewPresenter.showView(this);

    }

    //todo 语音录单修改商品
    public void updateGoodForVoiceView(GoodBean goodBean) {
        mCreateOrderUiPre.updateGoodForVoice(goodBean);
    }


    public void initView() {
        mHeaderView = findViewById(R.id.headerView);
        mDrawerLayout = findViewById(R.id.drawerLayout);
        mLeftMenuFragment = (LeftMenuFragment) getSupportFragmentManager().findFragmentById(R.id.leftMenuView);
        mDrawerLayout.setScrimColor(getColorById(R.color.color_transp80));
        setLeftMenuItemClickListener();
        mHeaderView.setOnLogoClickListener(view -> mDrawerLayout.openDrawer(GravityCompat.START));
        mHeaderView.setOnBackClickListener(view -> {
            mHeaderView.hidBackView();
            mainPresenter.showMainUI();
        });
        //todo 左边关闭后，在执行其他操作，不然可能感觉卡顿
        mDrawerLayout.addDrawerListener(new MyDrawerLayoutListener() {
            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
                showFunctionUI();
            }
        });

    }


    private void showFunctionUI() {
        if (mCurrentMenuData == null) return;
        // todo 有开单权限才显示 返回开单按钮
        if (sConfigData.hasCreateOrderPermission()) {
            //显示返回按钮
            mHeaderView.showBackView();
        }
        //订单管理
        mainPresenter.showFunctionUI(mCurrentMenuData, mHeaderView);
        mCurrentMenuData = null;
    }


    private void setLeftMenuItemClickListener() {
        mLeftMenuFragment.setListener(menuData -> {
            mCurrentMenuData = menuData;
            //隐藏侧滑菜单
            mDrawerLayout.closeDrawer(Gravity.LEFT);

        });
    }


    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            ToastUtil.showToast("再按一次退出");
            mExitTime = System.currentTimeMillis();
        } else {
            AppUtil.exitApp();
            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onDestroy() {
        DeviceManger.onDestroy(null);
        super.onDestroy();
    }

    public void startConnection() {
        if (!mWeightBlueManger.isConnection()) {
            mIsNeedNt = true;
            startConnectionBlue();
        }
    }


    //网页那边更新数据，这边同步更新
    public void updateCustom(int type, CustomBean customBean) {
        CustomBean choiceCustomBean = ChoiceCustomData.newInstance().getCustomBean();
        if (choiceCustomBean == null) {
            return;
        }
        //todo 修改的客户和我们主界面使用的客户是一个，需要更新主界面。
        if (choiceCustomBean.getId() == customBean.getId()) {
            if (type == 1) { //该客户被删除了，使用默认散客数据
                getDefaultCustom();
            } else if (type == 2) {//修改操作
                updateCustom(customBean);
                ChoiceCustomData.newInstance().setCustomBean(customBean);
            }
        }

    }


    //更新客户信息
    public void updateCustom(CustomBean customBean) {
        EvenBusUtil.updateHomeDefaultCustorm(customBean);
    }


    public void showMainUI() {
        mainPresenter.showMainUI();
        mHeaderView.hidBackView();
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        if (event.getCode() == EventBusType.CONNECTION_DEVICE.getType()) {
            DeviceBean deviceBean = (DeviceBean) event.getData();
            if (deviceBean != null) {
                if (mWeightBlueManger != null) {
                    mWeightBlueManger.connection(deviceBean, getActivity(), mListener);
                }
            }

        } else if (event.getCode() == EventBusType.TO_AFTERSALEVIEW.getType()) {
            OrderDetailBean orderDetailBean = (OrderDetailBean) event.getData();
            mainPresenter.showAftersaleFragment(orderDetailBean);
        } else if (event.getCode() == EventBusType.CREATE_GOOD.getType()) {
            mainPresenter.showCreateGoodUI((GoodListBean) event.getData());
        }
        else if (event.getCode() == EventBusType.CREATE_CUSTORM.getType()) {
            mainPresenter.showCreateCustormUI((CustomBean) event.getData());
        }
    }
}


